package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.dtos.WmScanDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 马毅爽
 * @description 针对表【wm_news(自媒体图文内容信息表)】的数据库操作Service实现
 * @createDate 2023-12-03 20:32:25
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        // 1. 检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 获取当前的登录用户
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 获取分页参数
        Page<WmNews> p = new Page<WmNews>(dto.getPage(), dto.getSize()).addOrder(new OrderItem("created_time", false));
        // 4. 条件查询
        Page<WmNews> page = lambdaQuery().eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus()).between(dto.getEndPubDate() != null && dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate()).eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId()).like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword()).eq(WmNews::getUserId, user.getId()).page(p);
        // 5. 返回分页结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());

        return result.ok(page.getRecords());
    }

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 发布修改文章或保存为草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        // 0. 条件判断
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 1. 保存和修改文章
        WmNews wmNews = new WmNews();
        // 属性拷贝
        wmNews = BeanUtil.copyProperties(dto, WmNews.class);
        // 封面图片
        if (dto.getImages() != null && !dto.getImages().isEmpty()) {
            String imagesStr = StrUtil.join(",", dto.getImages());
            wmNews.setImages(imagesStr);
        }
        // 如果当前封面类型为自动 -1
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }

        saveOrUpdateWmNews(wmNews);
        // 2. 判断是否为草稿，如果为草稿结束当前方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        // 3. 不是草稿，保存文章内容图片与素材的关系
        // 获取到文章内容中的图片信息
        List<String> materials = ectractUrlInfo(dto.getContent());
        // 保存文章与素材的关系
        saveRelativeInfoForContent(materials, wmNews.getId());
        // 4. 不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto, wmNews, materials);

        //审核文章
//        wmNewsAutoScanService.autoScanWnNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        // 1. 检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章不存在");
        }
        // 3. 判断文章状态
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章未发布");
        }
        // 4. 修改文章
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            lambdaUpdate().set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, dto.getId()).update();
            // 发送消息，通知article修改文章的配置
            if (wmNews.getArticleId() != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("articleId", wmNews.getArticleId());
                map.put("enable", dto.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 查询新闻列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listVo(WmScanDto dto) {
        // 1. 检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 获取分页参数
        Page<WmNewsVo> p = new Page<WmNewsVo>(dto.getPage(), dto.getSize()).addOrder(new OrderItem("created_time", false));
        // 3. 查询列表
        Page<WmNewsVo> page = wmNewsMapper.queryPage(p, dto);
        // 4. 返回结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        return result.ok(page.getRecords());
    }

    @Override
    public ResponseResult voDetail(Integer id) {
        // 检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 获取数据
        WmNewsVo newsVo = wmNewsMapper.getOne(id);
        return ResponseResult.okResult(newsVo);
    }

    @Override
    public ResponseResult authFail(WmScanDto dto) {
        // 校验参数
        if (dto.getId() == null || StrUtil.isBlank(dto.getMsg())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 修改状态
        lambdaUpdate()
                .set(WmNews::getStatus, WmNews.Status.FAIL.getCode())
                .set(WmNews::getReason, dto.getMsg())
                .eq(WmNews::getId, dto.getId())
                .update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private static final String PASS = "审核成功";

    @Override
    public ResponseResult authPass(WmScanDto dto) {
        // 校验参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 修改状态
        lambdaUpdate()
                .set(WmNews::getStatus, WmNews.Status.ADMIN_SUCCESS.getCode())
                .set(WmNews::getReason, PASS)
                .eq(WmNews::getId, dto.getId())
                .update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 功能1：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1.如果内容图大于1，小于3 单图 type 1
     * 2.如果内容图片大于3 多图 type 3
     * 3.如果内容没有图片 无图 type 0
     * <p>
     * 功能2：保存封面图片与素材的关系
     *
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();

        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (materials.size() >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (!materials.isEmpty()) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            // 修改文章
            if (images != null && !images.isEmpty()) {
                wmNews.setImages(StrUtil.join(",", images));
            }
            updateById(wmNews);
        }
        if (images != null && !images.isEmpty()) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 保存文章内容和图片的关系
     *
     * @param materials
     * @param id
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer id) {
        saveRelativeInfo(materials, id, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 保存文章图片与素材的关系到数据库中
     *
     * @param materials
     * @param id
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer id, short type) {
        if (materials != null && !materials.isEmpty()) {
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(new LambdaQueryWrapper<WmMaterial>().in(WmMaterial::getUrl, materials));
            // 判断素材是否有效
            if (materials == null || materials.isEmpty()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            if (materials.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelations(materialIds, id, type);
        }
    }

    /**
     * 提取文章中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<Map> maps = JSON.parseArray(content, Map.class);
        List<String> images = new ArrayList<>();
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                images.add((String) map.get("value"));
            }

        }
        return images;
    }


    private void saveOrUpdateWmNews(WmNews wmNews) {
        // 补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);

        if (wmNews.getId() == null) {
            // 保存
            save(wmNews);
        } else {
            // 修改
            // 删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }

    }
}




